<template>
  <div>
    <div class="tree">
      <a-tree
        v-model="checkedKeys"
        checkable
        :expanded-keys="expandedKeys"
        :default-checked-keys="selectKey"
        :auto-expand-parent="autoExpandParent"
        :selected-keys="selectedKeys"
        :default-expandAll="true"
        :tree-data="plainOptions"
        @expand="onExpand"
        @select="onSelect"
      >
      </a-tree>
    </div>
  </div>
</template>
<script>
import { mapActions, mapState } from 'vuex'
export default {
  props: ['type','checkedList', 'plainOptions', 'dataAllKeys'],
  data() {
     return {
      expandedKeys: ['tenant_1'], //默认展开
      autoExpandParent: true,
      checkedKeys: [], //选中
      selectedKeys: [],
      selectKey: [],
      treeData: [],
      dataOptions: []
    };
  },
  watch: {
    checkedList(val) {
      console.log(val)
      this.checkedKeys = val
    },
    // 监听选中的值传给父组件【防止初次打开编辑plainOptions过慢】
    plainOptions(val) {

      this.dataOptions = []
      this.dataOptions = this.filterData(val, this.checkedKeys)
      this.checkedKeys = this.dataOptions.map(v => v.value)
    },
    checkedKeys(val) {
      this.dataOptions = []
      this.dataOptions = this.filterData(this.dataAllKeys, val)

      let obj = {
        data: val, //选中的值
        dataOptions: this.dataOptions, //选中的数组对象
        type: this.type
      }
      this.$emit('setCheckedKeys', obj)
    },
  },
  methods: {
    onExpand(expandedKeys) {
      // console.log('onExpand', expandedKeys);
      // if not set autoExpandParent to false, if children expanded, parent can not collapse.
      // or, you can remove all expanded children keys.
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      // console.log('onCheck', checkedKeys);
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      // console.log('onSelect', info);
      this.selectedKeys = selectedKeys;
    },
    // datas需筛选的数组集，checkedKeys选中的数组值
    filterData(datas, checkedKeys) {
      return datas.filter(item => checkedKeys.indexOf(item.value) > -1)
    }
  },
};
</script>

